package Socket;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
聊天室的服务器端

为了实现聊天资源的共享
 */
public class Server4 {

    private ServerSocket serverSocket;//声明一个 电话总机  serverSocket

    ArrayList<PrintWriter> allOut =new ArrayList<>();//该集合用于保存客户端的输出流，用于广播信息

    public Server4() {
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }  //无参构造，在创建服务器对象时候创建端口并赋值端口号

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println( "客户端"+socket.getInetAddress()+"已经连接");
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }
            //循环接电话，并创建新的线程-->调用  电话处理  方法

            /*服务器接收消息*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server4 server = new Server4();
        server.start();
    }//main方法中创建服务器对象，并开启服务器start方法

    /*
     * 定义内部类与客户端交互
     * */
    private class ClientHandler implements Runnable {
        private Socket socket;  //在服务器 声明一个socket
        private String host;  //记录客户端IP地址

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }//用构造方法把“外接来的电话 转到的 服务器的socket”接收

        @Override
        public void run() {
            try {
                //服务器接收信息
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                InetAddress inetAddress = socket.getInetAddress();//服务器的地址

                //服务器发送消息
                OutputStream out=socket.getOutputStream();
                OutputStreamWriter osw=new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw=new BufferedWriter(osw);
                PrintWriter pw=new PrintWriter(bw,true);


                allOut.add(pw);


                String host=String.valueOf(inetAddress);
                String subAd=host.substring(host.lastIndexOf('.'));
                String message;
                try {
                    while ((message = br.readLine()) != null) {

                        for(PrintWriter o:allOut){
                            o.println(subAd+" said: "+ message);
                        }
                    }
                } catch (IOException e) {
                    System.out.println("大概率是客户端"+subAd+"异常退出...");
                }
            } catch (IOException e) {

            }

        }
    }


}
